<template>
  <view class="index">
    <view class="center">
      <view class="ind_from">
        <view class="row">
          <view class="label">末次月经日期</view>
          <view class="value">
            <picker
              mode="date"
              :start="minDate"
              :end="maxDate"
              @change="changeStartDateChange"
            >
              <view class="uni-input">{{ starDate ? starDate : "请选择日期" }}</view>
            </picker>
          </view>
        </view>
        <view class="row">
          <view class="label">平均月经周期</view>
          <view class="value">
            <view class="step-btn" @click="cycle = Math.max(20, Number(cycle)-1)">-</view>
            <input class="input" type="number" v-model="cycle" min="20" max="45" style="width:60rpx;text-align:center;" />
            <view class="step-btn" @click="cycle = Math.min(45, Number(cycle)+1)">+</view>
            <text style="margin-left: 8px;">天</text>
          </view>
        </view>
      </view>
      <view class="btn" @click="submit">开始计算</view>
      <view class="result">
        <view class="row"><view class="label">今天是</view><view class="value">{{ today }}</view></view>
        <view class="row"><view class="label">预产期</view><view class="value">{{ result.date || '--' }}</view></view>
        <view class="row"><view class="label">您已怀孕</view><view class="value">{{ result.pregnantDays !== undefined ? result.pregnantDays + '天（' + result.pregnantWeeks + '周）' : '--' }}</view></view>
        <view class="row"><view class="label">距离宝宝出生</view><view class="value">{{ result.leftDays !== undefined ? result.leftDays + '天' : '--' }}</view></view>
        <view class="progress-bar">
          <view class="progress-bg">
            <view class="progress-inner" :style="{width: progressPercent + '%'}"></view>
          </view>
          <view class="progress-text">孕期进度：{{ showResult ? progressPercent + '%' : '--' }}</view>
        </view>
        <view class="tips-area">
          <view class="tips-title">本周孕期小贴士</view>
          <view class="tips-content">{{ showResult ? tips : '请先填写信息并点击计算' }}</view>
        </view>
        <button class="addShortcut" open-type="addShortcut" :bindaddshortcut="eventHandler">添加到桌面</button>
        <button class="share" open-type="share">分享</button>
      </view>
      <view class="sub_text">
        <view class="p red bold">温馨提示：</view>
        <view class="p">预产期计算器可以根据您的月经周期，轻松准确地进行预产期计算！整个孕期约为40周（280天）。</view>
        <view class="p">预产期计算方法：末次月经第一天起，月份加9，日期加7。例如：末次月经是1月1日，加9个月为10月1日，再加7天，为10月8日。</view>
        <view class="p">实际分娩日期与推算的预产期可能会有1-2周差异，如不清楚末次月经日期，请以医生建议为准。</view>
      </view>
      <view class="pub_ad_banner">
        <!-- #ifdef MP-TOUTIAO -->
        <ad
          :unit-id="adBannerIdDouyin"
          :ad-intervals="30"
          :fixed="false"
          type="banner"
          scale="100"
        />
        <!-- #endif -->
        <!-- #ifdef MP-KUAISHOU -->
        <ad :type="100011054" :unit-id="adBannerIdKuaishou"></ad>
        <!-- #endif -->
      </view>
    </view>
  </view>
</template>

<script>
import {
  showAdConfirmModal,
  adVideoShow,
  adBannerIdDouyin,
  adBannerIdKuaishou,
} from "@/common/ad";
export default {
  data() {
    return {
      adBannerIdDouyin: adBannerIdDouyin,
      adBannerIdKuaishou: adBannerIdKuaishou,
      starDate: "",
      showResult: false,
      isUnlock: false,
      result: {
        date: "",
      },
      cycle: 28,
      today: "",
      tipsList: [
        '保持良好心情，适当运动有助于胎儿健康。',
        '孕期注意营养均衡，多吃蔬菜水果。',
        '定期产检，关注胎儿发育情况。',
        '避免熬夜，保证充足睡眠。',
        '孕期补充叶酸，预防胎儿神经管缺陷。',
      ],
      tips: '',
      minDate: '',
      maxDate: '',
    };
  },
  mounted() {
    // 设置日期选择范围
    const now = new Date();
    const yyyy = now.getFullYear();
    const mm = String(now.getMonth() + 1).padStart(2, '0');
    const dd = String(now.getDate()).padStart(2, '0');
    this.maxDate = `${yyyy}-${mm}-${dd}`;
    this.minDate = `${yyyy - 1}-${mm}-${dd}`;
    this.today = `${yyyy}-${mm}-${dd}`;
  },
  computed: {
    progressPercent() {
      // 孕期总天数280天
      return Math.min(100, Math.round((this.result.pregnantDays / 280) * 100));
    },
  },
  methods: {
    eventHandler(e) {
      if (e.detail.errNo) {
        this.global.toast("添加到桌面失败");
      } else {
        this.global.toast("添加到桌面成功");
      }
    },
    changeStartDateChange(e) {
      this.starDate = e.detail.value;
    },
    calculateDueDate(lmp, cycle) {
      // 解析末次月经日期
      const date = new Date(lmp);
      // 计算周期差异（默认28天，用户可自定义）
      const cycleDiff = Number(cycle) - 28;
      // 在月份上加9个月
      date.setMonth(date.getMonth() + 9);
      // 在日期上加7天+周期差异
      date.setDate(date.getDate() + 7 + cycleDiff);
      // 如果加天数后超过了该月的天数，回滚到该月的最后一天
      if (
        date.getDate() >
        new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate()
      ) {
        date.setDate(
          new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate()
        );
      }
      // 返回格式化的预产期
      return date.toISOString().split("T")[0];
    },
    getResult() {
      // 计算预产期
      const dueDate = this.calculateDueDate(this.starDate, this.cycle);
      // 今天日期
      const today = new Date(this.today);
      // 末次月经日期
      const lmpDate = new Date(this.starDate);
      // 已怀孕天数
      const pregnantDays = Math.floor((today - lmpDate) / (1000 * 60 * 60 * 24));
      // 已怀孕周数
      const pregnantWeeks = Math.floor(pregnantDays / 7);
      // 预产期日期
      const due = new Date(dueDate);
      // 距离宝宝出生天数
      const leftDays = Math.max(0, Math.floor((due - today) / (1000 * 60 * 60 * 24)));
      this.result = {
        date: dueDate,
        pregnantDays: pregnantDays > 0 ? pregnantDays : 0,
        pregnantWeeks: pregnantWeeks > 0 ? pregnantWeeks : 0,
        leftDays: leftDays,
      };
      this.showResult = true;
      // 随机小贴士
      this.tips = this.tipsList[Math.floor(Math.random() * this.tipsList.length)];
    },
    submit() {
      if (this.starDate == "") {
        this.global.toast("请选择末次月经第一天");
        return;
      }
      if (!this.isUnlock) {
        showAdConfirmModal(() => {
          try {
            adVideoShow(() => {
              this.getResult();
            });
          } catch (error) {
            this.getResult();
          }
        });
      } else {
        this.getResult();
      }
    }
  },
};
</script>

<style scoped lang="scss">
.top-banner {
  width: 100%;
  margin: 0 auto 24rpx auto;
  display: flex;
  justify-content: center;
}
.banner {
  width: 320rpx;
  height: 120rpx;
  border-radius: 16rpx;
  object-fit: cover;
}
.step-btn {
  width: 48rpx;
  height: 48rpx;
  line-height: 48rpx;
  background: #ffe4ec;
  color: #ff69b4;
  border: none;
  border-radius: 50%;
  font-size: 32rpx;
  margin: 0 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.progress-bar {
  margin: 24rpx 0 0 0;
  .progress-bg {
    width: 100%;
    height: 18rpx;
    background: #ffe4ec;
    border-radius: 9rpx;
    overflow: hidden;
  }
  .progress-inner {
    height: 18rpx;
    background: linear-gradient(90deg, #ffb6c1 0%, #ff69b4 100%);
    border-radius: 9rpx;
    transition: width 0.4s;
  }
  .progress-text {
    font-size: 22rpx;
    color: #b36a7a;
    margin-top: 6rpx;
    text-align: right;
  }
}
.tips-area {
  background: #fff0f6;
  border-radius: 12rpx;
  padding: 18rpx 16rpx;
  margin: 24rpx 0 0 0;
  .tips-title {
    color: #ff69b4;
    font-size: 26rpx;
    font-weight: bold;
    margin-bottom: 6rpx;
  }
  .tips-content {
    color: #b36a7a;
    font-size: 24rpx;
    line-height: 1.7;
  }
}
.share-btn {
  margin: 32rpx auto 0 auto;
  display: block;
  width: 80%;
  background: linear-gradient(90deg, #ffb6c1 0%, #ff69b4 100%);
  color: #fff;
  font-size: 30rpx;
  border-radius: 32rpx;
  padding: 16rpx 0;
  text-align: center;
  font-weight: bold;
  letter-spacing: 2rpx;
  box-shadow: 0 4px 16px #f7e3e9;
  border: none;
}
.ind_from {
  background: #fff7f0;
  margin-top: 30rpx;
  border: 4rpx solid #f7c7d2;
  border-radius: 16rpx;
  box-shadow: 0 2px 8px #f7e3e9;
  .row {
    padding: 24rpx 24rpx;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f3dbe2;
    &:last-child {
      border-bottom: 0;
    }
    .label {
      width: 180px;
      flex-shrink: 0;
      color: #b36a7a;
      font-size: 30rpx;
    }
    .value {
      width: 100%;
      display: flex;
      align-items: center;
      .input {
        width: 120rpx;
        border: 1px solid #f7c7d2;
        border-radius: 8rpx;
        padding: 8rpx 12rpx;
        font-size: 28rpx;
        background: #fff;
        color: #b36a7a;
      }
    }
  }
}
.btn {
  margin: 40rpx 0 0 0;
  background: linear-gradient(90deg, #ffb6c1 0%, #ff69b4 100%);
  color: #fff;
  text-align: center;
  padding: 20rpx 0;
  border-radius: 32rpx;
  font-size: 32rpx;
  font-weight: bold;
  letter-spacing: 2rpx;
  box-shadow: 0 4px 16px #f7e3e9;
}
.result {
  background: #fff7f0;
  margin-top: 30rpx;
  border: 4rpx solid #f7c7d2;
  border-radius: 16rpx;
  padding: 24rpx 16rpx;
  .row {
    display: flex;
    align-items: center;
    padding: 12rpx 0;
    .label {
      width: 180px;
      color: #b36a7a;
      font-size: 28rpx;
    }
    .value {
      color: #ff69b4;
      font-size: 30rpx;
      font-weight: bold;
    }
  }
}
.sub_text {
  text-align: left;
  padding: 36rpx 0 0 0;
  font-size: 24rpx;
  color: #b36a7a;
  .red {
    color: #ff69b4;
    font-size: 26rpx;
    line-height: 1.8;
  }
  .bold {
    font-weight: bold;
  }
}
.pub_ad_banner {
  margin-top: 40rpx;
}
.addShortcut,
.share {
  margin: 16rpx auto 0 auto;
  display: block;
  width: 80%;
  background: #fff;
  color: #ff69b4;
  font-size: 30rpx;
  border-radius: 32rpx;
  padding: 16rpx 0;
  text-align: center;
  font-weight: bold;
  letter-spacing: 2rpx;
  border: 2rpx solid #ff69b4;
  box-shadow: 0 2px 8px #f7e3e9;
}
</style>
